import socket,  threading

this_ip = '0.0.0.0'
this_port = 6000
g_conn_pool = []


def start_server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (this_ip, this_port)
    server_socket.bind(server_address)
    server_socket.listen(5)
    print("服务端已启动，等待客户端连接...")
    return server_socket

def handle_client(client_socket):
    try:
        while True:
            send_msg = input("发送: ")
            #设置退出条件
            if send_msg == "q":
                break
            send_msg = send_msg
            #发送数据，编码
            client_socket.send(send_msg.encode("utf-8"))

            message_bytes = client_socket.recv(1024)
            if not message_bytes:
                client_socket.close()
                g_conn_pool.remove(client_socket)
                break
            print('message_bytes:', message_bytes, client_socket, type(client_socket))


    except socket.error as e:
        print(f'Error in client connection: {e}')
    finally:
        client_socket.close()


if __name__ == "__main__":
    server_socket = start_server()

    try:
        while True:
            client_socket, client_address = server_socket.accept()
            print(f'Connected all user: {g_conn_pool}')
            print(f'Connected by client: {client_address}')
            client_thread = threading.Thread(target=handle_client, args=(client_socket,))
            client_thread.setDaemon(True)
            client_thread.start()
    except Exception as e:
        print(f"Server error: {e}")
    finally:
        server_socket.close()